package com.wenzhoujie;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.model.LatLng;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.wenzhoujie.constant.Constant.SearchTypeMap;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.MapsearchBase_listModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.MapsearchActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;

/**
 * 地图附近
 * 
 * @author js02
 * 
 */
public class MapSearchActivity extends BaseBaiduMapActivity
{
	/**
	 * -1:全部，0：优惠券；1：活动；2：团购；3：代金券；4：商家 。 传进来的值请引用SearchTypeMap类的常量
	 */
	public static final String EXTRA_SEARCH_TYPE = "extra_search_type";

	public static final String EXTRA_BASE_LIST_MODEL = "extra_base_list_model";

	private int mSearchType;

	@ViewInject(id = R.id.act_nearby_map_ll_bot)
	private LinearLayout mLlBot = null;

	private HttpHandler mHandler = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		setmTitleType(TitleType.TITLE_SIMPLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_map_search);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init()
	{
		getIntentData();
		initTitle();
	}

	@Override
	public void onMapLoaded()
	{
		super.onMapLoaded();
		startLocation(true);
	}

	private void getIntentData()
	{
		mSearchType = getIntent().getIntExtra(EXTRA_SEARCH_TYPE, SearchTypeMap.TUAN);
	}

	private void initTitle()
	{
		mTitleSimple.setmListener(new SDTitleSimpleListener()
		{

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v)
			{
				startLocation(true);
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v)
			{
				finish();
			}
		});
		mTitleSimple.setTitleTop("地图");
		mTitleSimple.setRightText("当前位置");
	}

	private void requestMapsearch_tuanInterface()
	{

		if (mHandler != null)
		{
			mHandler.cancel();
		}

		RequestModel model = new RequestModel();
		model.put("act", "mapsearch");
		if (mLlCurrent != null)
		{
			model.put("m_latitude", mLlCurrent.latitude);
			model.put("m_longitude", mLlCurrent.longitude);
		}
		model.put("type", mSearchType);// -1:全部，0：优惠券；1：活动；2：团购；3：代金券；4：商家
		if (mLlTopLeft != null)
		{
			model.put("latitude_top", mLlTopLeft.latitude);
			model.put("longitude_left", mLlTopLeft.longitude);
		}
		if (mLlBottomRight != null)
		{
			model.put("latitude_bottom", mLlBottomRight.latitude);
			model.put("longitude_right", mLlBottomRight.longitude);
		}
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				MapsearchActModel actModel = JsonUtil.json2Object(responseInfo.result, MapsearchActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (mBaiduMap != null)
					{
						mBaiduMap.clear();
					}
					addOverlays(actModel);
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{

			}
		};
		mHandler = InterfaceServer.getInstance().requestInterface(model, handler);
	}

	private void addOverlays(MapsearchActModel actModel)
	{
		switch (mSearchType)
		{
		case SearchTypeMap.ALL:
			addAllOverlays(actModel);
			break;
		case SearchTypeMap.YOU_HUI:
			addOverlays(actModel.getYouhui_list());
			break;
		case SearchTypeMap.EVENT:
			addOverlays(actModel.getEvent_list());
			break;
		case SearchTypeMap.TUAN:
			addOverlays(actModel.getTuan_list());
			break;
		case SearchTypeMap.MERCHANT:
			addOverlays(actModel.getMerchant_list());
			break;

		default:
			break;
		}
	}

	private void addAllOverlays(MapsearchActModel actModel)
	{
		addOverlays(actModel.getYouhui_list());
		addOverlays(actModel.getEvent_list());
		addOverlays(actModel.getTuan_list());
		addOverlays(actModel.getDaijin_list());
		addOverlays(actModel.getMerchant_list());
	}

	private void addOverlays(List<? extends MapsearchBase_listModel> listModel)
	{
		if (listModel != null && listModel.size() > 0)
		{
			MapsearchBase_listModel model = null;
			for (int i = 0; i < listModel.size(); i++)
			{
				model = listModel.get(i);
				if (model != null)
				{
					double xpoint = model.getXpointFormat();
					double ypoint = model.getYpointFormat();
					int type = model.getTypeFormat();

					LatLng ll = new LatLng(ypoint, xpoint);

					Bundle data = new Bundle();
					data.putSerializable(EXTRA_BASE_LIST_MODEL, model);

					addMarkerToMap(ll, getMark(type), data);
				}
			}
		}
	}

	/**
	 * 根据type获取类型图标
	 * 
	 * @param type
	 * @return
	 */
	private BitmapDescriptor getMark(int type)
	{
		switch (mSearchType)
		{
		case SearchTypeMap.YOU_HUI:
			return getMarkerFromResource(R.drawable.ic_map_youhui);
		case SearchTypeMap.EVENT:
			return getMarkerFromResource(R.drawable.ic_map_event);
		case SearchTypeMap.TUAN:
			return getMarkerFromResource(R.drawable.ic_map_tuan);
		case SearchTypeMap.MERCHANT:
			return getMarkerFromResource(R.drawable.ic_map_merchant);
		default:
			return getMarkerFromResource(R.drawable.ic_map_default);
		}
	}

	@Override
	public void onMapStatusChangeFinish(MapStatus mapStatus)
	{
		super.onMapStatusChangeFinish(mapStatus);
		requestMapsearch_tuanInterface();
	}

	@Override
	public boolean onMarkerClick(Marker marker)
	{
		super.onMarkerClick(marker);
		MapsearchBase_listModel model = showInfoWindow(marker);
		// TODO 底部信息绑定
		bindBottomData(model);
		return true;
	}

	/**
	 * 显示marker点击弹出窗口
	 * 
	 * @param marker
	 */
	private MapsearchBase_listModel showInfoWindow(Marker marker)
	{
		final MapsearchBase_listModel model = (MapsearchBase_listModel) marker.getExtraInfo().getSerializable(EXTRA_BASE_LIST_MODEL);
		if (model != null)
		{
			View mPopView = getLayoutInflater().inflate(R.layout.pop_act_nearbyshopsmap, null);

			TextView tvName = (TextView) mPopView.findViewById(R.id.act_nearbyshoppopview_tv_name);
			TextView tvSubName = (TextView) mPopView.findViewById(R.id.act_nearbyshoppopview_tv_sub_name);

			tvName.setText(model.getSupplier_name());
			tvSubName.setText(model.getName());

			OnInfoWindowClickListener listener = new OnInfoWindowClickListener()
			{
				public void onInfoWindowClick()
				{
					Intent intent = new Intent();
					switch (model.getTypeFormat())
					{
					case SearchTypeMap.YOU_HUI:
						intent.putExtra(YouHuiDetailActivity.EXTRA_YOUHUI_ID, model.getId());
						intent.setClass(MapSearchActivity.this, YouHuiDetailActivity.class);
						break;
					case SearchTypeMap.EVENT:
						intent.putExtra(EventsDetailActivity.EXTRA_EVENTS_ID, model.getId());
						intent.setClass(MapSearchActivity.this, EventsDetailActivity.class);
						break;
					case SearchTypeMap.TUAN:
						intent.putExtra(TuanDetailActivity.EXTRA_GOODS_ID, model.getId());
						intent.setClass(MapSearchActivity.this, TuanDetailActivity.class);
						break;
					case SearchTypeMap.MERCHANT:
						intent.putExtra(MerchantDetailNewActivity.EXTRA_MERCHANT_ID, model.getId());
						intent.setClass(MapSearchActivity.this, MerchantDetailNewActivity.class);
						break;

					default:
						break;
					}
					startActivity(intent);
					mBaiduMap.hideInfoWindow();
				}
			};
			mInfoWindow = new InfoWindow(mPopView, marker.getPosition(), listener);
			mBaiduMap.showInfoWindow(mInfoWindow);
		}
		return model;
	}

	/**
	 * 绑定底部信息
	 * 
	 * @param model
	 */
	private void bindBottomData(final MapsearchBase_listModel model)
	{
		if (model != null)
		{
			mLlBot.removeAllViews();
			getLayoutInflater().inflate(R.layout.include_map_bot_info, mLlBot);
			TextView tvTitle = (TextView) findViewById(R.id.include_map_bot_info_tv_title);
			TextView tvContent = (TextView) findViewById(R.id.include_map_bot_info_tv_content);
			Button btnSearch = (Button) findViewById(R.id.include_map_bot_info_btn_search);

			SDViewBinder.setTextView(tvTitle, model.getSupplier_name());
			SDViewBinder.setTextView(tvContent, model.getAddress());

			btnSearch.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View view)
				{
					double lat = SDTypeParseUtil.getDoubleFromString(model.getYpoint(), 0);
					double lon = SDTypeParseUtil.getDoubleFromString(model.getXpoint(), 0);

					Intent intent = new Intent(getApplicationContext(), RouteInformationActivity.class);
					intent.putExtra(RouteInformationActivity.EXTRA_END_LAT, lat);
					intent.putExtra(RouteInformationActivity.EXTRA_END_LON, lon);

					intent.putExtra(RouteInformationActivity.EXTRA_END_NAME, model.getAddress());
					startActivity(intent);
				}
			});
		}
	}

	@Override
	public void onMapClick(LatLng ll)
	{
		super.onMapClick(ll);
		if (mInfoWindow != null)
		{
			mBaiduMap.hideInfoWindow();
		}
	}

	private void clickSearch()
	{
		// if (mModel != null)
		// {
		// SDViewBinder.setTextView(mTvTitle, mModel.getName());
		// SDViewBinder.setTextView(mTvContent, mModel.getApi_address());
		//
		// double lat = SDTypeParseUtil.getDoubleFromString(mModel.getYpoint(),
		// 0);
		// double lon = SDTypeParseUtil.getDoubleFromString(mModel.getXpoint(),
		// 0);
		//
		// Intent intent = new Intent(getApplicationContext(),
		// RouteInformationActivity.class);
		// intent.putExtra(RouteInformationActivity.EXTRA_END_LAT, lat);
		// intent.putExtra(RouteInformationActivity.EXTRA_END_LON, lon);
		//
		// intent.putExtra(RouteInformationActivity.EXTRA_END_NAME,
		// mModel.getApi_address());
		// startActivity(intent);
		// }
	}
}